//
//  YBPicTransitionVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/26.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBPicTransitionVC.h"

#import <TXLiteAVSDK_Professional/TXVideoEditer.h>
#import "TCVideoPreview.h"
#import "PhotoTransitionToolbar.h"
#import "YBProgressObj.h"
#import "TCVideoEditViewController.h"

@interface YBPicTransitionVC ()<TXVideoGenerateListener,TCVideoPreviewDelegate,TransitionViewDelegate>
@property(nonatomic,strong) TXVideoEditer *ugcEdit;
@property(nonatomic,strong) TCVideoPreview  *videoPreview;
@property(nonatomic,strong) PhotoTransitionToolbar *photoTransitionToolbar;
@property(nonatomic,strong)UIButton *nextBtn;
@property CGFloat  duration;

@end

@implementation YBPicTransitionVC {
    NSString    *_videoOutputPath;
    CGFloat _leftTime;
    CGFloat _rightTime;
    CGFloat bottomToolbarHeight;
    CGFloat bottomInset;
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarHidden = YES;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_videoPreview setPlayBtn:NO];
    [_videoPreview playVideo];
}
- (void)dealloc {
    [_videoPreview removeNotification];
    _videoPreview = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate =nil;
    
    self.subNavi.backgroundColor = UIColor.clearColor;
    _videoOutputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"ybPicTransition.mp4"];
    _leftTime = 0;
    bottomToolbarHeight = 52;
    bottomInset = 10;
    
    [self.view addSubview:self.videoPreview];
    [self setmaskView];
    [self.view addSubview:self.photoTransitionToolbar];
    [self.view addSubview:self.nextBtn];
    [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_photoTransitionToolbar);
        make.width.equalTo(@(65));
        make.height.equalTo(@30);
        make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    
    TXPreviewParam *param = [[TXPreviewParam alloc] init];
    param.videoView = _videoPreview.renderView;
    param.renderMode =  PREVIEW_RENDER_MODE_FILL_EDGE;
    _ugcEdit = [[TXVideoEditer alloc] initWithPreview:param];
    _ugcEdit.generateDelegate = self;
    _ugcEdit.previewDelegate = _videoPreview;
    
    int listFps = 30;
    if (_imageList.count>7) {
        listFps = 23;
    }else if (_imageList.count>5){
        listFps = 25;
    }
    [_ugcEdit setPictureList:_imageList fps:listFps];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self onVideoTransitionLefRightSlipping];
    });
    
    [self.view bringSubviewToFront:self.naviView];
}
- (void)clickNaviLeftBtn {
    
    YBWeakSelf;
    NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),@"msg":YZMsg(@"是否退出视频编辑"),@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            [weakSelf pause];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
   
}
- (void)pause {
    [_ugcEdit pausePlay];
    [_videoPreview setPlayBtn:NO];
}

#pragma mark TransitionViewDelegate
- (void)_onVideoTransition:(TXTransitionType)type {
    __weak __typeof(self) weakSelf = self;
    [_ugcEdit setPictureTransition:type duration:^(CGFloat duration) {
        _duration = duration;
        _rightTime = duration;
        [weakSelf.ugcEdit startPlayFromTime:0 toTime:weakSelf.duration];
        [weakSelf.videoPreview setPlayBtn:YES];
    }];
}

- (void)onVideoTransitionLefRightSlipping {
    [self _onVideoTransition:TXTransitionType_LefRightSlipping];
}

- (void)onVideoTransitionUpDownSlipping {
    [self _onVideoTransition:TXTransitionType_UpDownSlipping];
}

- (void)onVideoTransitionEnlarge {
    [self _onVideoTransition:TXTransitionType_Enlarge];
}

- (void)onVideoTransitionNarrow {
    [self _onVideoTransition:TXTransitionType_Narrow];
}

- (void)onVideoTransitionRotationalScaling {
    [self _onVideoTransition:TXTransitionType_RotationalScaling];
}

- (void)onVideoTransitionFadeinFadeout {
    [self _onVideoTransition:TXTransitionType_FadeinFadeout];
}

#pragma mark TXVideoGenerateListener
-(void) onGenerateProgress:(float)progress {
    [YBProgressObj progressManeger].generationHidden = NO;
    [YBProgressObj progressManeger].generationProgress = progress;
}
-(void)destoryProgressView {
    [YBProgressObj progressManeger].generationHidden = YES;
    [[YBProgressObj progressManeger] progressDestroy];
}
-(void) onGenerateComplete:(TXGenerateResult *)result {
    [self destoryProgressView];
        
    if (result.retCode == 0) {
        
        TCVideoEditViewController *vc = [[TCVideoEditViewController alloc] init];
        [vc setVideoPath:_videoOutputPath];
        vc.musicPath = _musicPath;
        vc.musicID = _musicID;
        vc.haveBGM = _haveBGM;
        vc.isTakeSame = _isTakeSame;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:vc animated:YES];
    }else{
        YBWeakSelf;
        NSString *msg = [NSString stringWithFormat:@"%ld\n%@",(long)result.retCode,result.descMsg];
        NSDictionary *contentDic = @{@"title":@"",@"msg":msg,@"left":@"",@"right":YZMsg(@"确定"),@"richImg":@""};
        [YBAlertView showAlertView:contentDic complete:^(int eventType) {
            [weakSelf clickNaviLeftBtn];
        }];
    }
    
}

#pragma mark VideoPreviewDelegate
- (void)onVideoPlay {
    [_ugcEdit startPlayFromTime:_leftTime toTime:_rightTime];
}

- (void)onVideoPause
{
    [_ugcEdit pausePlay];
}

- (void)onVideoResume {
    [self onVideoPlay];
}

- (void)onVideoPlayProgress:(CGFloat)time {
    _leftTime = time;
}

- (void)onVideoPlayFinished {
    _leftTime = 0;
    [_ugcEdit startPlayFromTime:_leftTime toTime:_rightTime];
}

- (void)onVideoEnterBackground {
    if ([[YBProgressObj progressManeger] isExist]) {
        [_ugcEdit pauseGenerate];
    }else{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_ugcEdit pausePlay];
        [_videoPreview setPlayBtn:NO];
    }
}

- (void)onVideoWillEnterForeground {
    if ([[YBProgressObj progressManeger] isExist]) {
        [_ugcEdit resumeGenerate];
    }
}

#pragma mark - get/set

-(void)setmaskView {
    UIImageView* mask_top = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [mask_top setImage:[UIImage imageNamed:@"video_record_mask_top"]];
    [self.view addSubview:mask_top];
    
    UIImageView* mask_buttom = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 100, self.view.frame.size.width, 100)];
    [mask_buttom setImage:[UIImage imageNamed:@"video_record_mask_buttom"]];
    [self.view addSubview:mask_buttom];
}
- (TCVideoPreview *)videoPreview {
    if (!_videoPreview) {
        _videoPreview = [[TCVideoPreview alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) coverImage:nil];
        _videoPreview.delegate = self;
    }
    return _videoPreview;
}
- (PhotoTransitionToolbar *)photoTransitionToolbar {
    if (!_photoTransitionToolbar) {
        _photoTransitionToolbar = [[PhotoTransitionToolbar alloc] initWithFrame:CGRectMake(0, self.view.height - bottomInset - bottomToolbarHeight-ShowDiff, self.view.width-90, bottomToolbarHeight)];
        _photoTransitionToolbar.delegate = self;
    }
    return _photoTransitionToolbar;
}
- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setTitle:YZMsg(@"下一步") forState:0];
        _nextBtn.titleLabel.font = SYS_Font(14);
        [_nextBtn setTitleColor:[UIColor whiteColor] forState:0];
        _nextBtn.backgroundColor = Pink_Cor;
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.layer.cornerRadius = 15;
        [_nextBtn addTarget:self action:@selector(clickNextBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}
-(void)clickNextBtn {
    [self pause];
    [_videoPreview setPlayBtn:NO];
    //图片编辑只能走正常生成逻辑，这里使用高码率，保留更多图片细节
    [[YBProgressObj progressManeger] setUpViewCancelHidden:YES andComplete:nil];
    [YBProgressObj progressManeger].generationHidden = NO;
    
    [_ugcEdit setVideoBitrate:10000];
    [_ugcEdit setCutFromTime:0 toTime:_rightTime];
    [_ugcEdit quickGenerateVideo:VIDEO_COMPRESSED_540P videoOutputPath:_videoOutputPath];
    
}
- (BOOL)prefersStatusBarHidden {
    return NO;
}
@end
